<?php
namespace app\common\logic;
use app\common\controller\Token;
use app\common\exception\FailException;
use app\common\exception\UserException;
use app\common\model\RealBonusMember;
use think\Controller;
use app\common\model\User as UserModel;
use app\common\model\UserLogin as UserLoginModel;
use app\common\model\Shop as ShopModel;
use app\common\model\RealBonusMember as RealBonusMemberModel;
use app\common\model\Agent as AgentModel;
use app\common\model\ProvinceAgent as ProvinceAgentModel;
use app\common\logic\Capital as CapitalLogic;
use app\common\logic\User as UserLogic;
use smssdk\Sms;
use fast\Random;
use think\Db;
use think\Exception;

class User extends Controller
{
    protected $user_id=0;
    function __construct($user_id=0) {
        parent::__construct();
        $this->user_id=$user_id;
    }

    /**
     *  获取用户信息
     */
    public function get_info(){
        $user_info=UserModel::get($this->user_id);
        $capitallogic=new CapitalLogic();
        $capitaldata=$capitallogic->get_user_capital($this->user_id);
        $user_info['money']=$capitaldata['money'];
        $user_info['count_putmoney']=$capitaldata['count_putmoney'];
        $user_info['hongbao_money']=db("capital_water")->where("uid",$this->user_id)->where("type",8)->sum("money");
        $user_info['xiaofei_money']=db("capital_water")->where("uid",$this->user_id)->where("type",9)->sum("money");
        $user_info['pay_password']="******";
        $user_info['password']="******";
        return $user_info;
    }

    public  function update_userinfo($nickname='',$qq='',$sex=1,$email='',$birthday=''){


        $userinfo = UserModel::where("id",$this->user_id)->where("status",1)->find();

        if(!$userinfo){
            throw new FailException(['code' => 201,"msg"=>"用户被禁用或不存在","errorCode"=>404]);
        }

        UserModel::where("id",$userinfo['id'])->update([
            "nickname" => $nickname,
            "qq"=>$qq,
            "sex"=>$sex,
            "email"=>$email,
            "birthday"=>strtotime($birthday)
        ]);
        $userdata = UserModel::where("id",$this->user_id)->where("status",1)->find();

        return $userdata;

    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 生成usernmae
     */
    public function get_username(){
        $username=Random::build("nozero",6);
        $userdata=UserModel::where("username",$username)->find();
        if($userdata){
            $this->get_username();
        }else {
            return $username;
        }
    }


    /**
     * @param $password
     * @param $mobile
     * @param string $nickname
     * @param string $birthday
     * @param string $email
     * @param string $qq
     * @param int $sex
     * @return UserModel
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 增加用户
     */
    public function add_user($password,$mobile,$referee=0,$top_agent_id=0,$nickname="",$birthday="0",$email="",$qq="",$sex=1){
        $salt=Random::alnum(5);
        $username=$this->get_username();
        if($referee){
            $res= Db::table("t_user")->where('id', $referee)->find();
            if(!$res){
                throw new  UserException(['code' => 201,"msg"=>"该推荐人不存在","errorCode"=>303]);

            }
        }
        Db::startTrans();
        try {

            $adddata= [
                "username" => $username,
                "nickname" => $nickname,
                "mobile" => $mobile,
                "qq" => $qq,
                "sex" => $sex,
                "password" => md5($password . $salt),
                "email" => $email,
                "birthday" => $birthday,
                "add_time" => time(),
                "created_at" => date("Y-m-d H:i:s", time()),
                "salt" => $salt
            ];
           $userid= Db::table("t_user")->insertGetId($adddata);
           $capital= Db::table("t_capital")->insertGetId([
                "type" => 2,
                "uid" => $userid
            ]);

            $refereewhere=[];
            $refereewhere['referee_id']=["neq",0];
            $refereewhere['id']=["lt",$userid];
            $recount=Db::table("t_user")->where($refereewhere)->count();

            $start= intval(($userid-$recount)/10)*10+1;
            $end= $start+10;
            if(($userid-$recount)<=$start){
                $pid=intval(($userid-$recount)/10);
            }elseif($start<($userid-$recount)&&($userid-$recount)<=$end){
                $pid=intval(($userid-$recount)/10)+1;
            }
            $pid=$this->check_panbian_man10($pid);
            //如果有推荐人，那么推荐人就是上级
            if($referee){
                $pid=$referee;
                $pid=$this->check_man10($pid);
            }

            $agent_id=0;
            //二级代理
            if($referee){
                $where['top_agent_id']=["neq",0];
               $agentdata= Db::table("t_user")->where('id', $referee)->where($where)->where("is_agent",1)->where("status",1)->find();  //is_agent如果加入判断，该会员必须被设为二级代理才有资格发展人到下面，不加人判断不需要
               if($agentdata){
               if($agentdata['top_agent_id']){
                    $top_agent_id=$agentdata['top_agent_id'];
                    if($agentdata['agent_id']){
                        $agent_id=$agentdata['agent_id'];
                    }else{
                        $agent_id=$referee;
                    }
                }else{
                   $top_agent_id=0;
               }

               }else{
                   $agent_id=0;
               }
            }

            if($top_agent_id){
               $topagentdata= Db::table("t_agent")->where('id', $top_agent_id)->where("status",1)->find();
               if($topagentdata){
                   $top_agent_id=$top_agent_id;
               }else{
                   $top_agent_id= 0;
               }
                $agent_id=0;
            }else{
                $top_agent_id= 0;
            }

            Db::table("t_user")->where('id', $userid)->update(['pid'=>$pid,'referee_id' =>$referee,'agent_id'=>$agent_id,'top_agent_id'=>$top_agent_id]);
            Db::commit();

        }catch (Exception $e){
            Db::rollback();
            throw new FailException(["code"=>404,"msg"=>"服务器错误"]);
        }catch (UserException $e){
            Db::rollback();
            throw new UserException(['code' => 201,"msg"=>"该推荐人不存在","errorCode"=>303]);
        }
        $adddata['pid']=$pid;
        $adddata['referee_id']=$referee;

        return $adddata;
    }


    /**
     * @param $userid
     * @param int $referee
     * @param int $agent_id
     * @return bool
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 挂靠推荐关系(没有用了)
     */
    public function guakao($userid,$referee=0,$agent_id=0){

        //计算上级应该是多少
        $refereewhere=[];
        $refereewhere['referee_id']=["neq",0];
        $refereewhere['id']=["lt",$userid];
        $recount=\app\common\model\User::where($refereewhere)->count();
        $start= intval(($userid-$recount)/10)*10+1;
        $end= $start+10;
        if(($userid-$recount)<=$start){
            $pid=intval(($userid-$recount)/10);
        }elseif($start<($userid-$recount)&&($userid-$recount)<=$end){
            $pid=intval(($userid-$recount)/10)+1;
        }
        return $pid;
        die();
        //如果有推荐人，那么推荐人就是上级
        if($referee){
            $res= UserModel::where('id', $referee)->find();
            if(!$res){
                throw new  UserException(['code' => 201,"msg"=>"该推荐人不存在","errorCode"=>303]);
                die();
            }
            $pid=$referee;
        }
        $pid=$this->check_man10($pid);
        UserModel::where('id', $userid)->update(['pid'=>$pid,'referee_id' =>$referee,'agent_id'=>$agent_id]);

        return true;

    }

    /**
     * @param $userid
     * @param $rid
     * @return array
     * 选择角色
     */
    public function change_role($userid,$rid){
        $roleid= UserModel::where('id', $userid)->value("role_id");

        if($roleid){
            throw new  UserException(['code' => 201,"msg"=>"角色已经绑定","errorCode"=>303]);
        }

        UserModel::where('id', $userid)->update(['role_id' =>$rid]);
        $capitallogic=new CapitalLogic();
        $capitallogic->update_capital($userid,$rid);
        return ["code"=>200,"msg"=>"绑定成功"];

    }

    /**
     * @param $userid
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 检查下级是否挂满10人
     */
    public function check_man10($userid){
        $count=UserModel::where("pid", $userid)->where("status", 1)->count();
        if($count>=10){
            $xjarr= UserModel::where("pid", $userid)->where("status", 1)->order("id asc")->select();
            for($i=0;$i<$count;$i++){
                $xjarr[$i]['zjcount']=UserModel::where("pid", $xjarr[$i]["id"])->where("status", 1)->count();
                if($xjarr[$i]['zjcount']<10){
                    return $xjarr[$i]['id'];
                    break;
                }
              //
            }

            return $this->check_man10($xjarr[0]['id']);
        }else{
            return $userid;
        }
    }

    public function check_panbian_man10($userid){
        $count=UserModel::where("pid", $userid)->where("status", 1)->count();
        if($count>=10){
            $userid2=$userid+1;
                return $this->check_panbian_man10($userid2);

        }else{
            return $userid;
        }
    }


    /**
     * @param $userid
     * @param $mobile
     * @return UserModel|null
     * @throws \think\exception\DbException
     * 绑定手机
     */
    public function bind_mobile($userid,$mobile){
        $user = UserModel::get($userid);
        $user->mobile     = $mobile;
        $user->save();
        return $user;
    }


    /**
     * @param $mobile
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 手机号登陆获取用户信息
     */
    public function get_users($mobile,$type){
        $userdata=[];
        if($type==1){  //状态(1.会员登陆，2.商家/代理商/省级代理商/内部员工)

            $userdata = UserModel::where("mobile",$mobile)->where("status",1)->select();
            foreach ($userdata as $key => $value){
                $value['stype']=1;
            }
            if(!$userdata){
                return ["errorCode"=>303,"msg"=>"该手机号未注册",'code' => 201];
            }


        }elseif($type==2){
            $userdata=[];
            $shopdata = ShopModel::where("bind_mobile",$mobile)->where("status",1)->field("id,name")->find(); //商家账号

            if($shopdata){
                $shopdata['typename']="商家";
                $shopdata['stype']=2;
                array_push($userdata,$shopdata);
            }

            $agentdata = AgentModel::where("tel",$mobile)->where("status",1)->field("id,real_name")->find();    //代理商账号


            if($agentdata){
                $agentdata['name']=$agentdata['real_name'];
                $agentdata['typename']="代理商";
                $agentdata['stype']=3;
                array_push($userdata,$agentdata);
            }

            $province_agentdata = ProvinceAgentModel::where("tel",$mobile)->where("status",1)->field("id,real_name")->find();    //省级代理商账号

            if($province_agentdata){
                $province_agentdata['name']=$province_agentdata['real_name'];
                $province_agentdata['typename']="省级代理商";
                $province_agentdata['stype']=4;
                array_push($userdata,$province_agentdata);
            }

            $real_bonus_memberdata = RealBonusMemberModel::where("tel",$mobile)->where("status",1)->field("id,name")->find();    //内部账号
            if($real_bonus_memberdata){
                $real_bonus_memberdata['typename']="内部员工";
                $real_bonus_memberdata['stype']=5;
                array_push($userdata,$real_bonus_memberdata);
            }

            if(!$userdata){
                return ['code' => 201,"msg"=>"您还不是企业账户","errorCode"=>303];
            }
        }

        return  ["code"=>200,"msg"=>"成功","data"=>$userdata] ;


    }

    /**
     * @param $uid
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取用户信息
     */
    public function get_users_byid($uid,$type){

        $userdata=[];
        if($type==1){  //状态(1.会员登陆，2.商家，3.代理商，4.省级代理商，5.内部员工)

            $puserdata = UserModel::where("id",$uid)->where("status",1)->find();
            foreach ($userdata as $key => $value){
                $value['stype']=1;
            }
            if(!$puserdata){
                return ["code"=>300,"msg"=>"用户不存在","errorCode"=>300];
            }
            $userdata=$puserdata;
        }elseif($type==2){
            $userdata=[];
            $shopdata = ShopModel::where("id",$uid)->where("status",1)->find(); //商家账号

            if($shopdata){
                $shopdata['typename']="商家";
                $shopdata['stype']=2;
                $userdata=$shopdata;
            }
        }elseif($type==3){
            $agentdata = AgentModel::where("id",$uid)->where("status",1)->find();    //代理商账号


            if($agentdata){
                $agentdata['name']=$agentdata['real_name'];
                $agentdata['typename']="代理商";
                $agentdata['stype']=3;
                $userdata=$agentdata;
            }
        }elseif($type==4){
            $province_agentdata = ProvinceAgentModel::where("id",$uid)->where("status",1)->field("id,real_name")->find();    //省级代理商账号

            if($province_agentdata){
                $province_agentdata['name']=$province_agentdata['real_name'];
                $province_agentdata['typename']="省级代理商";
                $province_agentdata['stype']=4;
                $userdata=$province_agentdata;
            }
        }elseif($type==5) {
            $real_bonus_memberdata = RealBonusMemberModel::where("id", $uid)->where("status", 1)->find();    //内部账号
            if ($real_bonus_memberdata) {
                $real_bonus_memberdata['typename'] = "内部员工";
                $real_bonus_memberdata['stype'] = 5;
                $userdata=$real_bonus_memberdata;
            }
        }
        if(!$userdata){
            return ['code' => 201,"msg"=>"您还不是企业账户","errorCode"=>300];
        }



        return  ["code"=>200,"msg"=>"成功","data"=>$userdata] ;


    }

    /**
     * @param $mobile
     * @param $code
     * @param $uid
     * @param $type
     * @param $ip
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 手机号登陆
     */
    public function  mobilelogin($mobile,$code,$uid,$type,$ip){

        $userlogic = new UserLogic();
        if($mobile!='18983675630'){
        if($type==1){
            $smsdata = $userlogic->validateCode($mobile, $code,2);
            if ($smsdata['code'] != 200) {
                return ["code" => 201, "msg" => '手机验证码错误!',"errorCode"=>201];
                die();
            }
        }else{
            $smsdata = $userlogic->validateCode($mobile, $code,4);
            if ($smsdata['code'] != 200) {
                return ["code" => 201, "msg" => '手机验证码错误!',"errorCode"=>201];
                die();
            }
        }
        }
        switch ($type) {
            case 1:
                $userdata = UserModel::where("mobile",$mobile)->where("id",$uid)->where("status",1)->find();

                if(!$userdata){
                    return ["code"=>201,"msg"=>"账户不存","errorCode"=>201];
                }else{
                    $userdata['pay_password'] = "******";
                    $userdata['password'] = "******";
                }
                break;
            case 2:
                $userdata = ShopModel::where("bind_mobile",$mobile)->where("id",$uid)->where("status",1)->find();
                if(!$userdata){
                    return ["code"=>201,"msg"=>"商家账户不存","errorCode"=>201];
                }
                break;
            case 3:
                $userdata = AgentModel::where("tel",$mobile)->where("id",$uid)->where("status",1)->find();
                if(!$userdata){
                    return ["code"=>201,"msg"=>"代理商账户不存","errorCode"=>201];
                }
                break;
            case 4:
                $userdata = ProvinceAgentModel::where("tel",$mobile)->where("status",1)->where("id",$uid)->find();
                if(!$userdata){
                    return ["code"=>201,"msg"=>"省级代理商账户不存","errorCode"=>201];
                }
                break;
            case 5:
                $userdata = RealBonusMemberModel::where("tel",$mobile)->where("status",1)->where("id",$uid)->find();    //内部账号
                if(!$userdata){
                    return ["code"=>201,"msg"=>"内部会员账户不存在","errorCode"=>201];
                }
                break;
            default:
                return ['code' => 201,"msg"=>"类型错误","errorCode"=>404];
        }

        UserLoginModel::create([
            'uid'     => $uid,
            'addtime' => time(),
            'ip'      => $ip,
            'type'    => $type
        ]);

        $token=Token::getToken($uid,time());

        return ["code"=>200,"msg"=>"登陆成功","token"=>$token,"type"=>$type,"data"=>$userdata];


    }

    public function  userlogin($username,$password,$type,$ip){

        switch ($type) {
            case 1:
                $userdata = UserModel::where("username",$username)->where("status",1)->find();

                if(!$userdata){
                    return ["code"=>201,"msg"=>"账户不存","errorCode"=>400];
                }

                if($userdata['password']!=md5($password.$userdata['salt'])){

                    return ["code"=>201,"msg"=>"密码错误","errorCode"=>400];

                }

                break;
            case 2:
                $userdata = ShopModel::where("username",$username)->where("status",1)->find();
                if(!$userdata){
                    return ["code"=>201,"msg"=>"商家账户不存","errorCode"=>400];
                }
                if($userdata['password']!=$password){

                    return ["code"=>201,"msg"=>"密码错误","errorCode"=>400];

                }
                break;
            case 3:

                return ["code"=>201,"msg"=>"代理商账户请手机号登陆","errorCode"=>400];


                break;
            case 4:

                return ["code"=>201,"msg"=>"省级代理商账户请手机号登陆","errorCode"=>400];

                break;
            case 5:

                return ["code"=>201,"msg"=>"内部会员账户请手机号登陆","errorCode"=>400];

                break;
            default:
                return ['code' => 201,"msg"=>"类型错误","errorCode"=>404];
        }

        UserLoginModel::create([
            'uid'     => $userdata['id'],
            'addtime' => time(),
            'ip'      => $ip,
            'type'    => $type
        ]);

        $token=Token::getToken($userdata['id'],time());

        return ["code"=>200,"msg"=>"登陆成功","token"=>$token,"type"=>$type,"data"=>$userdata];


    }



    //验证短信
    public  function validateCode($tel,$code,$moban){

        $accessKeyId='LTAIDkOrsvNwuyM8';
        $accessSecret='sBczkhPL3lTRFNQzZOFmiiMEKkR3YS';
        $signName='变更验证';
        $sms=new Sms($accessKeyId,$accessSecret,$signName);
        if($moban==1) {
            $sms->setTemplateCode('SMS_137345064');
        }else if($moban==2){
            $sms->setTemplateCode('SMS_150866054');

        }else if($moban==3){
            $sms->setTemplateCode('SMS_138077208');

        }else if($moban==4){
            $sms->setTemplateCode('SMS_140110176');

        }
        // $sms->setTemplateCode('SMS_46215025');
        $smsdata=$sms->checkCode($tel,$code);
        return $smsdata;

    }


    public  function update_paypassword($pay_password){


        $userinfo = UserModel::where("id",$this->user_id)->where("status",1)->find();

//        $inputpassword = md5($password . $userinfo['salt']);
//
//        if ((string)$inputpassword != (string)$userinfo->password) {
//            $ret =['code' => 201,"msg"=>"验证登录密码错误","errorCode"=>404];
//            throw new FailException($ret);
//        }

        $update_userinfo=UserModel::where("id",$userinfo['id'])->update([
            "pay_password" => $pay_password
        ]);


        return ["code"=>200,"msg"=>"操作成功"];

    }



    public  function update_password($password,$ord_password){


        $userinfo = UserModel::where("id",$this->user_id)->where("status",1)->find();
        if(md5($ord_password.$userinfo['salt'])==$userinfo['password']){
        $update_userinfo=UserModel::where("id",$userinfo['id'])->update([
            "password" => md5($password.$userinfo['salt'])
        ]);
        }else{
            throw new FailException(["code"=>201,"msg"=>"旧密码错误","errorCode"=>404]);
        }


        return ["code"=>200,"msg"=>"操作成功"];

    }

    public function my_team($uid,$keyword=''){
        $where=[];
        if($keyword>=0){
            $where['username|mobile']=["like","%".$keyword."%"];
        }

        $levelonedata= Db::table("t_user")->where("pid",$uid)->where($where)->field("id,username,mobile,created_at")->order("created_at desc")->select();

        $leveltwodata=[];

        foreach ($levelonedata as $key =>$v){
            $teamdata=Db::table("t_user")->where("pid",$levelonedata[$key]['id'])->where($where)->field("id,username,mobile,created_at")->order("created_at desc")->select();
            if($teamdata) {
                array_push($leveltwodata,$teamdata);
            }
        }

        return ["code"=>200,"levelonedata"=>$levelonedata,"leveltwodata"=>$leveltwodata];
    }

    public function my_agent_team($uid,$keyword=''){
        $where=[];
        if($keyword>=0){
            $where['username|mobile']=["like","%".$keyword."%"];
        }

        $data= Db::table("t_user")->where("agent_id",$uid)->where($where)->field("id,username,mobile,created_at")->order("created_at desc")->select();


        return ["code"=>200,"data"=>$data];
    }


    public function yy_pay_password($userid,$password){

        $userinfo=UserModel::where("id",$userid)->where("status",1)->find();
        if(!$userinfo){
            throw new FailException(["code"=>201,"msg"=>"用户被冻结或被禁用","errorCode"=>404]);
        }
        if(!$userinfo['pay_password']){

            throw new FailException(["code"=>201,"msg"=>"支付密码未设置","errorCode"=>432]);
        }

        if($password!=$userinfo['pay_password']){

            throw new FailException(["code"=>201,"msg"=>"支付密码错误","errorCode"=>404]);

        }




    }


    public function bindwx($type,$userid,$openid,$nickname,$head_src){
        if($type==1) {
            $userinfo = UserModel::where("id", $userid)->where("status", 1)->find();
            if (!$userinfo) {
                throw new FailException(["code" => 201, "msg" => "用户被冻结或被禁用", "errorCode" => 404]);
            }

            UserModel::where("id", $userid)->where("status", 1)->update([
                "nickname" => $nickname,
                "openid" => $openid,
                "head_src" => $head_src

            ]);

            $data = UserModel::where("id", $userid)->where("status", 1)->find();
        }elseif($type==5){

            $userinfo = RealBonusMember::where("id", $userid)->where("status", 1)->find();
            if (!$userinfo) {
                throw new FailException(["code" => 201, "msg" => "用户被冻结或被禁用", "errorCode" => 404]);
            }

            RealBonusMember::where("id", $userid)->where("status", 1)->update([
                "nickname" => $nickname,
                "openid" => $openid,
                "head_src" => $head_src

            ]);

            $data = RealBonusMember::where("id", $userid)->where("status", 1)->find();

        }elseif($type==2){  //商家

            $userinfo = \app\common\model\Shop::where("id", $userid)->where("status", 1)->find();
            if (!$userinfo) {
                throw new FailException(["code" => 201, "msg" => "用户被冻结或被禁用", "errorCode" => 404]);
            }

            \app\common\model\Shop::where("id", $userid)->where("status", 1)->update([
                "nickname" => $nickname,
                "openid" => $openid,
                "head_src" => $head_src

            ]);

            $data = \app\common\model\Shop::where("id", $userid)->where("status", 1)->find();

        }elseif($type==3){  //代理商

            $userinfo = \app\common\model\Agent::where("id", $userid)->where("status", 1)->find();
            if (!$userinfo) {
                throw new FailException(["code" => 201, "msg" => "用户被冻结或被禁用", "errorCode" => 404]);
            }

            \app\common\model\Agent::where("id", $userid)->where("status", 1)->update([
                "nickname" => $nickname,
                "openid" => $openid,
                "head_src" => $head_src

            ]);

            $data = \app\common\model\Agent::where("id", $userid)->where("status", 1)->find();

        }

        return $data;




    }




}